import { createSelector, createSlice } from "@reduxjs/toolkit";
import uuid from "uuid-v4";

const expensesSlice = createSlice({
  name: "expenses",
  initialState: {
    list: [],
  },
  reducers: {
    addExpense: (state, action) => {
      state.list.push({
        id: uuid(),
        description: action.payload.description,
        amount: action.payload.amount,
      });
    },
    removeExpense: (state, action) => {
      const index = state.list.findIndex(
        (income) => income.id === action.payload.id
      );
      state.list.splice(index, 1);
    },
  },
});
// createSelector 是一个来自 reselect 库的函数，
// 用于创建 memoized selectors（记忆选择器）以优化 Redux 应用程序中的性能。
// 它有助于避免不必要的计算和渲染，特别是在应用程序的状态树很大或连接到组件的数据量很大时
// 它通常接收两个参数，
// 第一个是选择器，选择器从redux中获取数据，可以是一个也可以是多个数据
// 单个数据直接写就可以，多个使用数组的格式传递
// 第二个参数是一个计算函数，它接受前面选择器传过来的数据作为参数用于计算结果并输出
export const getTotalExpense = createSelector(
  totalExpenseSelector,
  calculateTotalExpense
);

export function totalExpenseSelector(state) {
  // console.log("222222", state);
  return state.expenses.list;
}

export function calculateTotalExpense(expensesList) {
  return expensesList.reduce((total, expense) => total + expense.amount, 0);
}

export const { addExpense, removeExpense } = expensesSlice.actions;

export default expensesSlice.reducer;
